<template>
  <div>
    <!-- 面包屑导航区域 -->
    <div>我觉得可以</div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 布局 -->
      <el-row :gutter="20">
        <el-col :span="7">
          <!-- 搜索框 -->
          <el-input placeholder="请输入搜索内容" v-model="queryInfoData.query" clearable
          @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" @click="showDialog">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 表格区域 -->
      <el-table
      :data="userData"
      border stripe
      style="width: 100%">
        <el-table-column type="index" label="#">
        </el-table-column>
        <el-table-column prop="username" label="姓名">
        </el-table-column>
        <el-table-column prop="email" label="邮箱">
        </el-table-column>
        <el-table-column prop="mobile" label="电话">
        </el-table-column>
        <el-table-column prop="role_name" label="角色">
        </el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model= "scope.row.mg_state" @change="stateChange(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 修改用户按钮 -->
            <el-tooltip class="item" effect="dark" content="修改" placement="top"
            :enterable="false">
              <el-button type="primary" icon="el-icon-edit" size="mini"
              @click="editTable(scope.row.id)">
              </el-button>
            </el-tooltip>
            <!-- 删除按钮 -->
            <el-tooltip class="item" effect="dark" content="删除" placement="top"
            :enterable="false">
              <el-button type="danger" icon="el-icon-delete" size="mini"
              @click="deleteTable(scope.row.id)">
              </el-button>
            </el-tooltip>
            <!-- 分配角色按钮 -->
            <el-tooltip class="item" effect="dark" content="分配角色" placement="top"
            :enterable="false" @click="giveRole(scope.row)">
              <el-button type="warning" icon="el-icon-s-tools" size="mini"
              @click="setupTable(scope.row)">
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
      @size-change="pagesizeChange"
      @current-change="pagenumChange"
      :current-page="queryInfoData.pagenum"
      :page-sizes="[1, 2, 5, 10]"
      :page-size="queryInfoData.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
      </el-pagination>
    </el-card>
    <!-- 添加用户对话框 -->
    <el-dialog
    title="添加用户"
    :visible.sync="dialogVisible"
    width="50%"
    @closed="restDialog">
      <!-- 添加用户表单 -->
      <el-form :model="addForm"
      :rules="addFormRules"
      ref="addFormRef"
      label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <!-- 取消按钮 -->
        <el-button @click="dialogVisible = false">取 消</el-button>
        <!-- 确定按钮 -->
        <el-button type="primary" @click="submitDialog">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户信息对话框 -->
    <el-dialog
    title="修改用户信息"
    :visible.sync="editDialogVisible"
    width="50%"
    @closed="restEditDialog">
      <el-form ref="editRef"
      :rules="editRules"
      :model="editData"
      label-width="70px">
        <el-form-item label="用户名">
          <el-input v-model="editData.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editData.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editData.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="subEditDialog">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog
    title="分配角色"
    :visible.sync="allotDialogVisible"
    width="50%"
    @closed="setRoleDialog">
      <div>
        <p>当前的用户: {{role.username}}</p>
        <p>当前的角色: {{role.role_name}}</p>
        <p>分配新角色:
          <el-select v-model="selectRoleId" placeholder="请选择">
            <el-option
            v-for="item in roleData"
            :key="item.id"
            :label="item.roleName"
            :value="item.id">
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="allotDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRolesDialog">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 邮箱的自定义校验规则
    const checkEmail = (rule, value, callback) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) return callback()
      callback(new Error('邮箱格式不符合要求,请重新输入'))
    }
    // 手机号的自定义校验规则
    const checkMobile = (rule, value, callback) => {
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value)) return callback()
      callback(new Error('邮箱格式不符合要求,请重新输入'))
    }
    return {
      // 获取数据请求参数对象
      queryInfoData: {
        query: '',
        pagenum: '1',
        pagesize: '2'
      },
      // 首次渲染请求得到的列表数据
      userData: [],
      // 数据总条数
      total: '',
      // 控制对话框的显示与隐藏
      dialogVisible: false,
      // 控制修改对话框的显示与隐藏
      editDialogVisible: false,
      // 控制分配角色对话框的显示与隐藏
      allotDialogVisible: false,
      // 被分配按钮选中保存的那行数据
      role: {},
      // 分配角色对话框下拉框绑定的数据
      roleData: [],
      // 分配角色对话框下拉框选中的id字符串
      selectRoleId: '',
      // 添加用户的数据
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 修改用户信息数据
      editData: {
        id: '',
        username: '',
        role_id: '',
        email: '',
        mobile: ''
      },
      // 添加用户表单的验证规则
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '用户长度在3~10个字符之间', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 7, max: 11, message: '长度在 7 到 11 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 修改对话框表单校验规则
      editRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get('users', { params: this.queryInfoData })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.userData = res.data.users
      this.total = res.data.total
    },
    // 监听每页几条pagesize尺寸变化
    pagesizeChange(newSize) {
      this.queryInfoData.pagesize = newSize
      this.getUserList()
    },
    // 监听当前页码值变化
    pagenumChange(newNum) {
      this.queryInfoData.pagenum = newNum
      this.getUserList()
    },
    // 监听状态开关变化
    async stateChange(state) {
      const { data: res } = await this.$http.put(`users/${state.id}/state/${state.mg_state}`)
      if (res.meta.status !== 200) {
        state.mg_state = !state.mg_state
        return this.$message.error('更新用户状态失败')
      }
      this.$message.success('更新用户状态成功')
    },
    // 监听对话框显示与隐藏
    showDialog() {
      this.dialogVisible = true
    },
    // 监听对话框关闭事件重置添加对话框
    restDialog() {
      this.$refs.addFormRef.resetFields()
    },
    // 监听对话框提交事件
    submitDialog() {
      this.$refs.addFormRef.validate(async val => {
        if (!val) return
        const { data: res } = await this.$http.post('users', this.addForm)
        if (res.meta.status !== 201) return this.$message.error('添加用户失败')
        // 添加成功时隐藏对话框并重新获取数据
        this.$message.success('添加用户成功')
        this.dialogVisible = false
        this.getUserList()
      })
    },
    // 根据id查询需要修改的表单数据信息
    async editTable(id) {
      this.editDialogVisible = true
      const { data: res } = await this.$http.get(`users/${id}`)
      if (res.meta.status !== 200) return this.$message.error('获取用户信息失败')
      this.editData = res.data
    },
    // 监听修改对话框的关闭事件
    restEditDialog() {
      this.$refs.editRef.resetFields()
    },
    // 监听修改对话框的数据更新事件
    subEditDialog() {
      this.$refs.editRef.validate(async val => {
        if (!val) return
        const { data: res } = await this.$http.put(`users/${this.editData.id}`, {
          email: this.editData.email,
          mobile: this.editData.mobile
        })
        if (res.meta.status !== 200) return this.$message.error('修改用户信息失败')
        this.editDialogVisible = false
        this.$message.success(res.meta.msg)
        this.getUserList()
      })
    },
    // 监听删除按钮事件
    async deleteTable(id) {
      const result = await this.$confirm('此操作将永久删除该用户信息, 是否继续?', '删除用户信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 用户确认删除返回值为字符串 confirm
      // 用户取消了删除返回值为字符串 concel
      if (result !== 'confirm') return this.$message.info('取消删除')
      const { data: res } = await this.$http.delete(`users/${id}`)
      if (res.meta.status !== 200) return this.$message.error('删除失败')
      this.$message.success(res.meta.msg)
      this.getUserList()
    },
    // 监听点击分配角色按钮事件
    async setupTable(role) {
      this.role = role
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取角色失败')
      this.roleData = res.data
      this.allotDialogVisible = true
    },
    // 监听分配角色对话框确定按钮事件
    async allotRolesDialog() {
      if (!this.selectRoleId) return this.$message.error('请选择需要分配的角色')
      const { data: res } = await this.$http.put(`users/${this.role.id}/role`, { rid: this.selectRoleId })
      if (res.meta.status !== 200) return this.$message.error('更新角色失败')
      this.$message.success('更新角色成功')
      this.getUserList()
      this.allotDialogVisible = false
    },
    // 监听分配角色对话框关闭事件
    setRoleDialog() {
      // 重置分配角色对话框下拉菜单id值
      this.selectRoleId = ''
      // 重置分配按钮选中的对象
      this.roleData = {}
    }
  }
}
</script>

<style lang="less" scoped>
.el-table {
  margin-top: 20px;
  font-size: 12px;
}
</style>
